package com.mysimplenews.utils;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by cxy on 2016/6/12.
 */
public class FragmentContainerProcess {

    private static FragmentContainerProcess fragmentContainer;
    private static FragmentActivity mFragActivity;
    private List<Fragment> fragments;
    private Fragment currentFragment;

    private FragmentContainerProcess(){
        fragments = new ArrayList<Fragment>();
    };

    public static FragmentContainerProcess getInstance(FragmentActivity fragmentActivity){
        mFragActivity = fragmentActivity;
        if(fragmentContainer == null)
            syncInit();
        return fragmentContainer;
    }

    private synchronized static void syncInit() {
        if(fragmentContainer == null)
            fragmentContainer = new FragmentContainerProcess();
    }

    public void addOrShowFragment(Fragment fragment,int layoutId){
        if(fragment == null)
            throw new ExceptionInInitializerError();
        if (currentFragment == fragment)
            return;
        if (!fragment.isAdded()) { // 如果当前fragment未被添加，则添加到Fragment管理器中
            if(currentFragment == null)
                mFragActivity.getSupportFragmentManager().beginTransaction()
                        .add(layoutId, fragment).commit();
            else
                 mFragActivity.getSupportFragmentManager().beginTransaction().hide(currentFragment)
                        .add(layoutId, fragment).commit();
        } else {
            mFragActivity.getSupportFragmentManager().beginTransaction().hide(currentFragment)
                    .show(fragment).commit();
        }

        currentFragment = fragment;
    }
}
